import os
import sys
import stat

CWD = os.getcwd()

def check_python_version():
    """
    Check python version.
    python3 is required, anaconda3 is better.
    """
    print('>>> Check python version.')
    
    current_python = sys.version_info[:2]
    required_python = (3, 5)
    
    if current_python < required_python:
        sys.stderr.write("""
==========================
Unsupported Python version
==========================
This version of lsfMonitor requires Python {}.{} (or greater version), 
but you're trying to install it on Python {}.{}.
""".format(*(required_python + current_python)))
        sys.exit(1)
    else:
        print('    Required python version : ' + str(required_python))
        print('    Current  python version : ' + str(current_python))

def gen_batch_run():
    """
    Generate script <BATCH_RUN_INSTALL_PATH>/bin/batch_run.
    """
    batch_run = str(CWD) + '/bin/batch_run'

    print('')
    print('>>> Generate script "' + str(batch_run) + '".')

    try:
        with open(batch_run, 'w') as BR:
             python_path = os.path.dirname(os.path.abspath(sys.executable))

             BR.write("""#!/bin/bash

# Set python3 path.
export PATH=""" + str(python_path) + """:$PATH

# Set install path.
export BATCH_RUN_INSTALL_PATH=""" + str(CWD) + """

# Execute batch_run.py.
python3 $BATCH_RUN_INSTALL_PATH/bin/batch_run.py $@
""")

        os.chmod(batch_run, stat.S_IRWXU+stat.S_IRWXG+stat.S_IRWXO)
    except Exception as err:
        print('*Error*: Failed on generating script "' + str(batch_run) + '": ' + str(err))
        sys.exit(1)

def gen_save_password():
    """
    Generate script <BATCH_RUN_INSTALL_PATH>/tools/save_password.
    """
    save_password = str(CWD) + '/tools/save_password'

    print('')
    print('>>> Generate script "' + str(save_password) + '".')

    try:
        with open(save_password, 'w') as SP:
             python_path = os.path.dirname(os.path.abspath(sys.executable))

             SP.write("""#!/bin/bash

# Set python3 path.
export PATH=""" + str(python_path) + """:$PATH

# Set install path.
export BATCH_RUN_INSTALL_PATH=""" + str(CWD) + """

# Execute save_password.py.
python3 $BATCH_RUN_INSTALL_PATH/tools/save_password.py $@
""")

        os.chmod(save_password, stat.S_IRWXU+stat.S_IRWXG+stat.S_IRWXO)
    except Exception as err:
        print('*Error*: Failed on generating script "' + str(save_password) + '": ' + str(err))
        sys.exit(1)

def gen_get_password():
    """
    Generate script <BATCH_RUN_INSTALL_PATH>/tools/get_password.
    """
    get_password = str(CWD) + '/tools/get_password'

    print('')
    print('>>> Generate script "' + str(get_password) + '".')

    try:
        with open(get_password, 'w') as SP:
             python_path = os.path.dirname(os.path.abspath(sys.executable))

             SP.write("""#!/bin/bash

# Set python3 path.
export PATH=""" + str(python_path) + """:$PATH

# Set install path.
export BATCH_RUN_INSTALL_PATH=""" + str(CWD) + """

# Execute get_password.py.
python3 $BATCH_RUN_INSTALL_PATH/tools/get_password.py $@
""")

        os.chmod(get_password, stat.S_IRWXU+stat.S_IRWXG+stat.S_IRWXO)
    except Exception as err:
        print('*Error*: Failed on generating script "' + str(get_password) + '": ' + str(err))
        sys.exit(1)

def gen_encrypt_python():
    """
    Generate script <BATCH_RUN_INSTALL_PATH>/tools/encrypt_python.
    """
    encrypt_python = str(CWD) + '/tools/encrypt_python'

    print('')
    print('>>> Generate script "' + str(encrypt_python) + '".')

    try:
        with open(encrypt_python, 'w') as SP:
             python_path = os.path.dirname(os.path.abspath(sys.executable))

             SP.write("""#!/bin/bash

# Set python3 path.
export PATH=""" + str(python_path) + """:$PATH

# Set install path.
export BATCH_RUN_INSTALL_PATH=""" + str(CWD) + """

# Execute encrypt_python.py.
python3 $BATCH_RUN_INSTALL_PATH/tools/encrypt_python.py $@
""")

        os.chmod(encrypt_python, stat.S_IRWXU+stat.S_IRWXG+stat.S_IRWXO)
    except Exception as err:
        print('*Error*: Failed on generating script "' + str(encrypt_python) + '": ' + str(err))
        sys.exit(1)

def gen_config_file():
    """
    Generate config file <BATCH_RUN_INSTALL_PATH>/config/config.py.
    """
    config_file = str(CWD) + '/config/config.py'

    print('')
    print('>>> Generate config file "' + str(config_file) + '".')
    
    if os.path.exists(config_file):
        print('*Warning*: config file "' + str(config_file) + '" already exists, will not update it.')
    else:
        try:
            with open(config_file, 'w') as CF:
                host_list = str(CWD) + '/config/host.list'

                CF.write('# Specify host list, default is "host.list" on current configure directory.\n')
                CF.write('HOST_LIST = "' + str(host_list) + '"\n')
                CF.write('\n')

                CF.write('# Valid ip format, for example, "10.212.20[67].\d+".\n')
                CF.write('VALID_IP_FORMAT = ""\n')
                CF.write('\n')
    
                CF.write('# Pre-ip, for example, "10.212.206".\n')
                CF.write('PRE_IP = ""\n')
                CF.write('\n')
    
                CF.write('# Default ssh command, for example, "ssh -X -o StrictHostKeyChecking=no".\n')
                CF.write('DEFAULT_SSH_COMMAND = ""\n')
                CF.write('\n')
    
            os.chmod(config_file, stat.S_IRWXU+stat.S_IRWXG+stat.S_IRWXO)
        except Exception as error:
            print('*Error*: Failed on opening config file "' + str(config_file) + '" for write: ' + str(error))
            sys.exit(1)

################
# Main Process #
################
def main():
    check_python_version()
    gen_batch_run()
    gen_save_password()
    gen_get_password()
    gen_encrypt_python()
    gen_config_file()

    print('')
    print('Done, Please enjoy it.')

if __name__ == '__main__':
    main()
